package com.yicheng.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;

import java.util.Date;
import java.util.Map;

public class JwtUtil {
    /**
     *过期5min
     */
    private static final long EXPIRE_TIME = 5 * 50 * 1000;

    /**
     * jwt密钥
     */
    private static final String SECRET = "nimasile";

    /**
     * 生成jwt字符串，五分钟后过期 Jwt(json web token)
     * @param userId
     * @param info, Map的value智能只能存放值的类型：Map, List, Boolean, Interger, Long, Double;
     * @return
     * */
    public static String sign(String userId, Map<String, Object> info) {
        try{
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            return JWT.create()
                    //将userId保存到token里面
                    .withAudience(userId)
                    //存放自定义数据Map
                    .withClaim("info", info)
                    //五分钟后过期
                    .withExpiresAt(date)
                    //token密钥
                    .sign(algorithm);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据token获取userID
     * @param  token
     * @return
     */
    public static String getUserId(String token) {
        try{
            return JWT.decode(token).getAudience().get(0);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public static boolean checkSign(String token){
        try{
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    //.withClaim("username", username)
                    .build();
            verifier.verify(token);
            return true;
        }catch (JWTVerificationException e) {
            throw new RuntimeException("token 无效，请重新获取");
        }
    }
}
